package com.zhiziai.aiproxy.config.security;

import com.zhiziai.aiproxy.constants.BusinessCode;
import com.zhiziai.aiproxy.dto.JsonVo;
import com.zhiziai.aiproxy.exception.AdminLoginTokenException;
import com.zhiziai.aiproxy.utils.JsonUtil;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(urlPatterns = "/*", filterName = "jWTAuthorizationFilter")
public class JWTAuthorizationFilter implements Filter {

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        if (request.getRequestURI().contains("/openai")
                || request.getRequestURI().contains("/admin")
                || request.getRequestURI().contains("/midjourney")
                || request.getRequestURI().contains("/aiProxy")
                ) {
            filterChain.doFilter(request, response);
            return;
        }
        String tokenHeader = null;
        Cookie[] cookies = request.getCookies();
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(JwtTokenUtils.TOKEN_COOKIE)) {
                    tokenHeader = cookie.getValue();
                }
            }
        }
        // 如果请求头中没有Authorization信息则直接放行了
        if (tokenHeader == null || !tokenHeader.startsWith(JwtTokenUtils.TOKEN_PREFIX)) {
//            response.sendRedirect("/chatGPT/login");
//            //返回json形式的错误信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
//            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = BusinessCode.NOLOGIN.getMsg();
            response.getWriter().write(JsonUtil.toJson(new JsonVo(BusinessCode.NOLOGIN.getValue(), reason)));
            response.getWriter().flush();
            return;
        }
        // 如果请求头中有token，则进行解析，并且设置认证信息
        try {
            String token = tokenHeader.replace(JwtTokenUtils.TOKEN_PREFIX, "");
            boolean expiration = JwtTokenUtils.isExpiration(token);

            if (expiration) {
                throw new AdminLoginTokenException("token超时了");
            } else {
                String username = JwtTokenUtils.getUsername(token);
                if (username != null) {
                    filterChain.doFilter(servletRequest, servletResponse);
                }
            }
        } catch (AdminLoginTokenException e) {
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            String reason = BusinessCode.ERRORTOKEN.getMsg() + " : " + e.getMessage();
            response.getWriter().write(JsonUtil.toJson(new JsonVo(BusinessCode.ERRORTOKEN.getValue(), reason)));
            response.getWriter().flush();
        }
    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
